package com.ruoyi.web.controller.app;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.ApiConstants;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class AppBaseController {


    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private ISysUserService iSysUserService;


    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 获取请求的用户Id
     *
     * @return 客户端Ip
     */
    public Long getUserId() {
        Object userId = request.getAttribute(ApiConstants.LOGIN_USER_KEY);
        if(null==userId){
            return null;
        }
        return Long.parseLong(userId.toString().trim());
    }

    /**
     * 获取请求的用户Id
     *
     * @return 客户端Ip
     */
    public String getUserName() {
        Object userId = request.getAttribute(ApiConstants.LOGIN_USER_KEY);
        if(null==userId){
            return "";
        }
        SysUser sysUser = iSysUserService.selectUserById((long)userId);
        if(null==sysUser||null==sysUser.getUserName()){
            return "";
        }
        return sysUser.getUserName();
    }

    /**
     * 获取请求的用户部门编码
     *
     * @return 客户端Ip
     */
    public String getUserDeptCode() {
        Object userId = request.getAttribute(ApiConstants.LOGIN_USER_KEY);
        if(null==userId){
            return "";
        }
        SysUser sysUser = iSysUserService.selectUserById((long)userId);
        if(null==sysUser||null==sysUser.getUserName()){
            return "";
        }
        return sysUser.getDeptCode();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

}
